package reflect;

import java.io.File;
import java.lang.reflect.Method;

/**
 * @author DBX
 * @effect 自动调用被AutoRunClass标注的类中被AutoRun标注的方法
 * @date 2021/09/16/10:13
 */
public class ReflectDemo12 {
    public static void main(String[] args)throws Exception {
        File file = new File(ReflectDemo12.class.getResource(".").toURI());
        File[] files = file.listFiles(f->f.getName().endsWith(".class"));
        for (File file1 : files) {
            String fileName = file1.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class c = Class.forName("reflect."+className);
            if (c.isAnnotationPresent(AutoRunClass.class)){
                System.out.println(className+"被标注了！");
                Object obj = c.newInstance();
//                获取所有方法
                Method[] methods = c.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRun.class)){
                        System.out.println(className+"的方法"+method.getName()+"()被标注了");


//                    通过该方法对象获取注解AutoRun
                    AutoRun autoRun = method.getAnnotation(AutoRun.class);
//                    通过AutoRun获取标注时传入的参数value值
                    int value = autoRun.value();
//                    根据value值调用该方法次数
                    for (int i = 0; i < value; i++) {
                        method.invoke(obj);
                    }
                    }
                }
            }
        }
    }
}
